import { defineComponent } from 'vue';
import 'quill/dist/quill.snow.css';
import Quill from 'quill';
import axios from 'axios';

const AppRichTextProps = {
  /**
   *  绑定值
   * @type {any}
   * @memberof AppRichTextProps
   */
  value: [String, Number],

  /**
   * 表单项名称
   * @type {String}
   * @memberof AppRichTextProps
   */
  name: String,

  /**
   * 是否禁用
   *
   * @type {boolean}
   * @memberof AppRichTextProps
   */
  disabled: Boolean,

  /**
   * 只读模式
   * @type {boolean}
   *  @memberof AppRichTextProps
   */
  readonly: Boolean,

  /**
   * placeholder值
   * @type {String}
   * @memberof AppRichTextProps
   */
  placeholder: String,

  /**
   * 模型服务
   * @type {String}
   * @memberof AppRichTextProps
   */
  modelService: Object,
};

export const AppRichText = defineComponent({
  name: 'AppRichText',
  props: AppRichTextProps,
  computed: {},
  methods: {
    /**
     * @description 文件上传
     * @param {*} file 文件
     */
    async uploadFile(base64: string) {
      const params = new FormData();
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      };
      const response: any = await axios.post(this.uploadUrl, params, config);
      if (response && response.data && response.status === 200) {
        //todo待测试
        // this.onSuccess(response);
      } else {
        // this.onError(response);
      }
    },
    /**
     * @description 成功
     * @param {*} response 响应
     * @param {*} file 上传文件
     */
    onSuccess(response: any) {
      this.$emit('editorValueChange', '');
    },

    /**
     * @description 上传失败
     * @param {*} error 错误
     * @param {*} file 文件
     */
    onError(error: any) {
      App.getNoticeService().error(`${(this as any).$tl('common.richtext.uploadfailed', '图片上传失败！')}`);
    },
  },
  setup: (prop: any, ctx: any) => {
    const toolbarOptions = [
      [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题字体
      ['bold', 'italic', 'underline', 'strike'], // 切换按钮
      ['blockquote', 'code-block'], // 文本块/代码块
      ['image'], // 图片 / 链接 / 视频
    ];
    const uploadUrl: string = `${App.getEnvironment()?.UploadFile}`;
    const quills: any = null;
    const content = '';
    const delta = null;
    return {
      toolbarOptions,
      quills,
      content,
      uploadUrl,
      delta,
    };
  },
  mounted() {
    this.quills = new Quill(`.rich-text-content-${this.name}`, {
      modules: {
        toolbar: this.toolbarOptions,
      },
      readOnly: this.readonly || this.disabled,
      theme: 'snow',
      placeholder: this.placeholder,
    });
    if (this.quills) {
      this.quills.root.innerHTML = this.value;
      this.quills.on('text-change', (delta: any, oldDelta: any, source: string) => {
        if (Object.is(source, 'user')) {
          const temptext = this.quills.getText();
          const text = temptext.trim().replace(/\s/g, '');
          const content = this.quills.getContents();
          const html = this.quills.root.innerHTML;
          if (delta.ops[0].insert && Object.is(typeof delta.ops[0].insert, 'object') && delta.ops[0].insert.image) {
            this.uploadFile(delta.ops[0].insert.image);
          }
          this.$emit('editorValueChange', html);
        }
      });
    }
  },
  render() {
    return (
      <div class='app-rich-text'>
        <div class={`rich-text-content-${this.name}`}></div>
      </div>
    );
  },
});
